/*
channel用于每一个socket连接的事件分发
*/

#pragma once

#include <sys/epoll.h>
#include <unistd.h>
#include <functional>
#include <memory>

using namespace std;

class EventLoop;
class HttpData;

class Channel{
private:
    using CallBack=function<void()>;
    CallBack m_readHandler;
    CallBack m_writeHandler;
    CallBack m_errorHandler;
    CallBack m_connHandler;
public:
    Channel(EventLoop *loop);
    Channel(EventLoop *loop, int fd);
    ~Channel();
    int getFd();
    void setHolder(std::shared_ptr<HttpData> holder);
    std::shared_ptr<HttpData> getHolder();
    void setReadHandler(CallBack &&readHandler){
        m_readHandler=readHandler;
    }
    void setWriteHandler(CallBack &&writeHandler) {
        m_writeHandler = writeHandler;
    }
    void setErrorHandler(CallBack &&errorHandler) {
        m_errorHandler = errorHandler;
    }
    void setConnHandler(CallBack &&connHandler) { 
        m_connHandler = connHandler; 
    }

    void handleRead();
    void handleWrite();
    void handleError(int fd, int err_num, std::string short_msg);
    void handleConn();
    void handleEvents();
    void setRevents(uint32_t ev);
    void setEvents(uint32_t ev);
    uint32_t& getEvents();
    bool EqualAndUpdateLastEvents();
    uint32_t getLastEvents();

private:
    EventLoop *m_loop;
    int m_fd;
    uint32_t m_events;          //关心的事件, 由用户设置
    uint32_t m_revents;         //目前活动的事件, 由Eventloop或Poller设置
    uint32_t m_last_events=0;   //最后一个事件
    //观测拥有本事件源的HTTP连接
    std::weak_ptr<HttpData> m_holder;
};